<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller\admin;
use App\Exception\ValidateException;
use function Hyperf\ViewEngine\view;
use Lengyue\Captcha\Captcha;
use Hyperf\DbConnection\Db;


class LoginController extends CommonController
{
	
	
	public function t(){
		return 'heyingmin';
	}
	
    public function login()
    {
		if($this->request->isMethod('get')){
			return view('admin/login/index');
		}else{
			$postField = 'username,password,verify,key';
			$data = $this->request->inputs(explode(',',$postField),'post');
			
			if (config('my.verify_status') && false === Captcha::check($data['verify'],$data['key'])) {
				throw new ValidateException("验证码错误");
			}
			
			$where['admin_user.user'] = trim($data['username']);
			$where['admin_user.pwd']  = md5(trim($data['password']).config('my.password_secrect'));
			
			$info = Db::table('admin_user')->join('role', 'admin_user.role_id','=','role.role_id')->select('admin_user.user_id','admin_user.name','admin_user.user as username','admin_user.status','role.role_id','role.status as role_status','role.access')->where($where)->first();
			
			if(!$info){
				throw new ValidateException("请检查用户名或者密码");
			}
			if(!($info->status) || !($info->role_status)){
				throw new ValidateException("该账户被禁用");
			}
			
			$info->access = explode(',',$info->access);
			
			$event['username'] = $data['username'];
			$event['application_name'] = 'admin';
			
			event(new \App\Event\LoginEvent($event));

			session()->set('admin',$info);
			session()->set('admin_auth_sign',data_auth_sign(object2array($info),config('my.password_secrect')));
			
			return ['status'=>200];
		}
    }
	
	
	
	//获取验证码状态
	public function verify(){
		$data['data'] = Captcha::base64();
		$data['verify_status'] = config('my.verify_status');	//验证码开关
		$data['status'] = 200;
	    return $data;
	}
	
	
	//阿里云oss上传异步回调返回上传路径，放到这是因为这个地址必须外部能直接访问到
	function aliOssCallBack(){
		$body = file_get_contents('php://input');
		header("Content-Type: application/json");
		$url = $this->getendpoint(config('my.ali_oss_endpoint')).'/'.str_replace('%2F','/',$body);
        return json(['code'=>1,'data'=>$url]);
	}
	
	
	//获取阿里云oss客户端上传地址
	private function getendpoint($str){
		if(strpos(config('my.ali_oss_endpoint'),'aliyuncs.com') !== false){
			if(strpos($str,'https') !== false){
				$point = 'https://'.config('my.ali_oss_bucket').'.'.substr($str,8);
			}else{
				$point = 'http://'.config('my.ali_oss_bucket').'.'.substr($str,7);
			}	
		}else{
			$point = config('my.ali_oss_endpoint');
		}
		return $point;
	}
	
	
   
}
